#include "MainWindow.h"

MainWindow::MainWindow():board_(),viewer_(board_){
    set_title("Reversi");
    add_events(Gdk::BUTTON_PRESS_MASK);
    add(viewer_);
    board_.add_viewer(&viewer_);
    std::cout << board_ << std::endl;
    viewer_.show();
}

bool MainWindow::on_button_press_event (GdkEventButton* event)
{

    gdouble x = event->x, y = event->y;
    int row , col;
    //Player click at the right place
    if(get_position((int)x, (int)y, row, col)){
        std::cout << "Human: " << "(" << row << ", " << col << ")" << std::endl;
        //valid move
        if(board_.valid_move(White, row, col)){
            //human's turn
            board_.move(White, row, col);
            //pc's turn
            if(board_.get_possible_move(Black, row, col) == Successful){
                std::cout << "Pc    : " << "(" << row << ", " << col << ")" << std::endl;
                board_.move(Black, row, col);
                while(board_.get_possible_move(White, row, col) == Unsuccessful &&
                      board_.get_possible_move(Black, row, col) == Successful){
                    std::cout << "Pc    : "
                              << "(" << row << ", " << col << ")" << std::endl;
                    board_.move(Black, row, col);
                }
            }
        }
        else{
            std::cout << "Invalid move" << std::endl;
        }
    }
    else{
        std::cout << "Out of board" << std::endl;
    }
    if(board_.get_possible_move(Black, row, col) == Unsuccessful &&
       board_.get_possible_move(White, row, col) == Unsuccessful){
        std::cout << "Game Over!" << std::endl;
    }
    std::cout << "PC    score: " << board_.score(Black) << std::endl;
    std::cout << "Human score: " << board_.score(White) << std::endl;

    return true;
}

bool
MainWindow::get_position(int x, int y, int& row, int& col)
{
    int window_width, window_height;
    get_size(window_width, window_height);
    int width = window_width / (Board::COLS+2);
    int height = window_height / (Board::ROWS+2);
    row = x / width;
    col = y / height;
    if( row == 0 || col == 0 || row == Board::ROWS + 1 || col == Board::COLS + 1){
        return false;
    }
    return true;
}

    
MainWindow:: ~MainWindow()
{}
